import Client from './base';
import * as uploader from '@yanxiu/uploader';
import { computeMd5 } from '../utils';

export default class SRTClient extends Client {
    run(callback) {
        const { file, id } = this;
        const config = this.config;
        const { onProgress, onSuccess, onError } = callback;

        /* "path/to/file_name.ext" */
        const key = computeMd5(file);
        const observable = uploader.upload(file, key, config);

        const observer = {
            complete: (data) => onSuccess({ id, data: { ...data, host: config.host, url: data.key, ispType: 'srt' } }),
            error: (info) => onError({ id, info }),
            progress: (progress) => {
                onProgress && onProgress({ id, progress: { percent: progress.total.percent } })
            },
        };

        this.subscription = observable.subscribe(observer);
    }

    abort() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }
}
